﻿using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;

public class Helper : MonoBehaviour
{
    public GameObject content;
    public Font font;

    public GameObject wait;
    public Slider slider;

    List<string> paths = new List<string>();
    //List<string> data = new List<string>();
    public string resultData;

    void Start()
    {
        Screen.SetResolution(960, 640, false);
    }

    public void Do()
    {
        paths.Clear();

        for (int i = 0; i < content.transform.childCount; i++) {
            GameObject go = content.transform.GetChild(i).gameObject;
            Destroy(go);
        }

        var path = WindowFileHelper.FolderBrowser();
        if (path != null && path.Length > 0) {
            StartCoroutine(coGetMd5(path));
        }
    }

    IEnumerator coGetMd5(string path)
    {
        wait.SetActive(true);
        getPath(path);
        int i = 0;
        int size = paths.Count;
        JsonData jsonData = new JsonData();
        foreach (string p in paths) {
            var subPath = p.Substring(path.Length + 1);
            var go = new GameObject();
            go.name = "item" + i;
            go.transform.parent = content.transform;
            var text = go.AddComponent<Text>();
            text.font = font;
            text.color = Color.black;
            text.horizontalOverflow = HorizontalWrapMode.Overflow;
            //string value = "" + subPath + " => <color=#0000FF>MD5: " + MD5.GetMD5HashFromFile(p) + "</color>";
            string md5Str;
            yield return md5Str = MD5.GetMD5HashFromFile(p);
            string value = "" + subPath + " => MD5: " + md5Str;
            JsonData jsonItem = new JsonData();
            jsonItem["path"] = subPath;
            jsonItem["md5"] = md5Str;
            jsonData[go.name] = jsonItem;

            slider.value = (float)i / (float)size;
            text.text = value;
            //Debug.Log("path: " + p + " MD5: " + MD5.GetMD5HashFromFile(p));
            i++;
        }
        wait.SetActive(false);
        //resultData = UniconToString(jsonData.ToJson());
        resultData = jsonData.ToJson();
        Debug.LogError("json data:" + resultData);
        Debug.LogError("json data:" + jsonData.ToString());
    }

    public void close()
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#else
        Application.Quit ();
#endif
    }

    public void publish()
    {
        string savePath = WindowFileHelper.GetSavePath();
        if (savePath != null && savePath.Length > 0) {
            Debug.Log("savePath: " + savePath);
            saveToFile(savePath);
        }
    }

    void getPath(string path)
    {
        if (path != null) {
            string[] f1 = System.IO.Directory.GetFiles(path, "*"); ;
            string[] d1;

            foreach (string f11 in f1) {
                //Debug.Log(f11);
                paths.Add(f11);
            }
            try {
                d1 = System.IO.Directory.GetDirectories(path);
                foreach (string d11 in d1) {
                    try {
                        getPath(d11);
                    } catch (System.Exception) { }
                }
            } catch (System.Exception) { }
        }
    }

    void saveToFile(string path)
    {
        if (path == null || path.Length <= 0)
            return;
        if (resultData == null || resultData.Length <= 0)
            return;

        Encoding encoding = Encoding.GetEncoding("utf-8");
        //Encoding encoding = Encoding.GetEncoding("gb2312");
        //写入文件
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) {
            using (TextWriter textWriter = new StreamWriter(fileStream, encoding)) {
                textWriter.Write(resultData);
            }
        }
    }
    /// <summary>
    /// 将Unicon字符串转成汉字String
    /// </summary>
    /// <param name="str">Unicon字符串</param>
    /// <returns>汉字字符串</returns>
    public string UniconToString(string str)
    {
        string outStr = "";
        if (!string.IsNullOrEmpty(str)) {
            string[] strlist = str.Replace("\\", "").Split('u');
            try {
                for (int i = 1; i < strlist.Length; i++) {
                    //将unicode字符转为10进制整数，然后转为char中文字符
                    outStr += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);
                }
            } catch (FormatException ex) {
                outStr = ex.Message;
            }
        }
        return outStr;
    }

}
